/**
 * @description: 定时刷新接口
 * @param {functipn} callback 需要执行的函数
 * @param {number} interval 间隔
 * @param {boolean} immediate 是否立刻执行
 * @param {array} dep 需要监听的变量
 */
import { useEffect } from 'react';

export default function useIntervalUpdate(callback, interval, immediate = false, dep = []) {
  let id;
  let time = +new Date();
  function redo() {
    const now = +new Date();
    if (now - time >= interval) {
      time = now;
      callback();
    }
    id = requestAnimationFrame(redo);
  }
  useEffect(() => {
    immediate && callback();
    redo();
    return () => {
      cancelAnimationFrame(id);
    };
  }, dep);
}
